﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace MDF.Utilites.Helper
{
    public class FileHelper
    {
        public static string CurrentDir
        {
            get
            {
                string strLogDirTemp = "";
                if (System.Web.HttpContext.Current != null)
                {
                    strLogDirTemp = System.Web.HttpContext.Current.Server.MapPath("~/");
                }
                if (string.IsNullOrEmpty(strLogDirTemp))
                {
                    strLogDirTemp = AppDomain.CurrentDomain.BaseDirectory;
                }

                return strLogDirTemp;
            }
        }

        public static bool WriteFile(string _strContent, string _strPath, string _strFileName, bool isOverride = false)
        {
            _strPath = _strPath.Replace("/", "\\");
            if (_strPath[0] == '\\')
                _strPath = _strPath.Substring(1);
            if (_strPath[_strPath.Length - 1] != '\\')
                _strPath += "\\";
            string strLogDirTemp = string.Format("{0}\\{1}", CurrentDir, _strPath);
            if (!Directory.Exists(strLogDirTemp))
                Directory.CreateDirectory(strLogDirTemp);
            string strFileSave = strLogDirTemp + _strFileName;
            StreamWriter stw = null;
            if (!File.Exists(strFileSave))
            {
                stw = System.IO.File.CreateText(strFileSave);
            }
            else
            {
                if (isOverride)
                    stw = new StreamWriter(strFileSave, true);
                else
                {
                    int iStart = strFileSave.LastIndexOf('.');
                    string strName = strFileSave.Substring(0, iStart);
                    string strLastName = strFileSave.Substring(iStart + 1, strFileSave.Length - iStart-1);
                    stw = new StreamWriter(strName + "_." + strLastName, true);
                }
            }
            stw.Write(_strContent);
            stw.Close();
            return true;
        }
    }
}
